package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时处理订单状态
 */
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理未付款超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeoutOrder(){
        //当前时间 - 15分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //根据订单状态为未付款和下单时间超过15分钟查询
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        if(ordersList != null && ordersList.size() > 0){
            for (Orders order : ordersList) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("超过15分钟未付款，订单已取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }


    /**
     * 处理一直处于配送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行一次
    public void processDeliveryOrder(){
        //当前时间凌晨1点 - 60分钟 = 0点
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //根据订单状态为配送中和下单时间小于0点查询
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){
            for (Orders order : ordersList) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }

    }

}
